//
//  LWMyQrcodeViewController.m
//  1.28  weibo
//
//  Created by mac on 15/1/31.
//  Copyright (c) 2015年 mac. All rights reserved.
//

#import "LWMyQrcodeViewController.h"
#import <CoreImage/CoreImage.h>

@interface LWMyQrcodeViewController ()
- (IBAction)closeClick:(id)sender;
@property (weak, nonatomic) IBOutlet UIImageView *qrcodeImageView;

@end

@implementation LWMyQrcodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    //1.创建滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    //2.还原滤镜的默认设置
    [filter setDefaults];
    //3.将要生成的数据转换成二进制
    NSData *data = [@"李伟" dataUsingEncoding:NSUTF8StringEncoding];
    //4.将数据设置给滤镜
    [filter setValue:data forKey:@"inputMessage"];
    //5.生成图片
    CIImage *qrcodeImage = [filter outputImage];
    //6.显示图片
    
    UIImage *Qimage = [self createNonInterpolatedUIImageFormCIImage:qrcodeImage withSize:600];
    UIImage *icon = [UIImage imageNamed:@"icon"];
    UIImage *resultImage = [self creatImageWithBackgreadImg:Qimage image:icon];
    self.qrcodeImageView.image = resultImage;
}

//将头像图片绘制到图形中

- (UIImage *)creatImageWithBackgreadImg:(UIImage *)backgreadImag image:(UIImage *)icon{

     //创建图形上下文
    UIGraphicsBeginImageContextWithOptions(backgreadImag.size, YES, 0.0);
    [backgreadImag drawInRect:CGRectMake(0, 0, backgreadImag.size.width, backgreadImag.size.height)];
    CGFloat W = 60;
    CGFloat H = 60;
    CGFloat X = (backgreadImag.size.width - icon.size.width)*0.5;
    CGFloat Y = (backgreadImag.size.height - icon.size.height)*0.5;
    [icon drawInRect:CGRectMake(X, Y, W, H)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;

}

/**
 *  根据CIImage生成指定大小的UIImage
 *
 *  @param image CIImage
 *  @param size  图片宽度
 */
- (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size
{
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 1.创建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

- (IBAction)closeClick:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
